<?php

namespace frontend\modules\resource\logic;


use common\models\BranchClass;
use common\models\ResourceClasses;
use frontend\modules\common\models\BaseHelper;
use frontend\modules\common\models\BaseParam;
use Yii;


/**
 * BranchSearch represents the model behind the search form of `common\models\Branch`.
 */
class ResourceClassesLogic
{

    /**
     * @param $id
     * @return bool
     * @throws \yii\base\ExitException
     */
    public function UpdateCateStatus($id)
    {
        if (!is_numeric($id))
            BaseHelper::Error('参数有误');
        $model = ResourceClasses::find()->where(['id' => $id])->one();
        if (empty($model))
            BaseHelper::Error('参数有误');
        $model->status = !$model->status;
        return $model->save(false);
    }


    /**
     * 总分类和分馆分类
     * @param $branchId
     * @return array
     * @throws \yii\base\ExitException
     */
    public function getBranchCate($branchId)
    {
        $allCate = $this->allClasses();
        $branchCate = $this->branchClasses($branchId);

        return compact('allCate', 'branchCate');
    }

    /**
     * 获取总分类
     * @return array
     * @throws \yii\base\ExitException
     */
    private function allClasses()
    {
        $classes = ResourceClasses::find()
            ->select(['id', 'pid as parent_id', 'title as label'])
            ->where(['status' => 1])
            ->indexBy('id')
            ->asArray()
            ->all();
        if (empty($classes))
            BaseHelper::Error('请先添加分类');

        return BaseParam::dealUnlimitedCate($classes);

    }

    /**获取店铺分类
     * @param $branchId
     * @return array
     */
    public function branchClasses($branchId)
    {
        $classes = BranchClass::find()
            ->select(['id', 'br_id', 'cat_id2'])
            ->where(['br_id' => $branchId])
            ->asArray()
            ->indexBy('cat_id2')
            ->all();
        if (empty($classes)) {
            return [];
        } else {
            return array_keys($classes);
        }
    }

    /**
     * @param $ids
     * @param $branchId
     * @return int
     * @throws \yii\base\ExitException
     * @throws \yii\db\Exception
     */
    public function changeBranchClasses($ids, $branchId)
    {

        //提交上来的东西
        if (empty($ids) || !is_array($ids))
            BaseHelper::Error('参数有误');
        //去过滤掉一级分类
        $ids = $this->classesFilter($ids);
        //先删除不再二级分类里的
        BranchClass::deleteAll(['and', ['not in', 'cat_id2', $ids], ['br_id' => $branchId]]);
        //再新增
        $res = $this->batchInsert($ids, $branchId);
        return $res;

    }

    /**
     * @param $ids
     * @return array
     * @throws \yii\base\ExitException
     */
    private function classesFilter($ids)
    {

        $res = ResourceClasses::find()
            ->select('id')
            ->where(['in', 'id', $ids])
            ->andWhere(['<>', 'pid', 0])
            ->indexBy('id')
            ->all();
        if (empty($res))
            BaseHelper::Error('参数有误');
        return array_keys($res);
    }

    /**
     * @param $ids
     * @param $branchId
     * @return int
     * @throws \yii\db\Exception
     */
    private function batchInsert($ids, $branchId)
    {
        $transaction = Yii::$app->db->beginTransaction();
        try {

            $sql = "INSERT IGNORE INTO `hy_branch_class` (`br_id`, `cat_id2`) VALUES ";
            $str = '';
            foreach ($ids as $key => $val) {
                $str .= '(' . $branchId . ',' . $val . ')' . ',';
            };
            $sql .= trim($str, ',');
            $res = Yii::$app->db->createCommand($sql)->execute();
            $transaction->commit();
            return $res;
        } catch (\yii\db\Exception $e) {
            $transaction->rollBack();
        }
    }

}
